package com.enqualcomm.kids.mvp.reai;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.enqualcomm.kids.R;

import common.utils.PlatformUtil;

/**
 * Created by Yinzhiqun on 2016/9/24.
 */

public class ShadowTransformer implements ViewPager.OnPageChangeListener, ViewPager.PageTransformer, HeaderAdapter.ItemClickListener {

    private ViewPager viewPager;
    private HeaderAdapter adapter;
    private View card_view;
    private ImageView card_view_shadow;
    private View card_view_content;

    public ShadowTransformer(ViewPager viewPager, HeaderAdapter adapter, View card_view, ImageView card_view_shadow) {
        this.adapter = adapter;
        this.viewPager = viewPager;
        this.card_view = card_view;
        card_view_content = ((ViewGroup) card_view).getChildAt(0);
        this.card_view_shadow = card_view_shadow;
        viewPager.addOnPageChangeListener(this);
        adapter.setItemClickListener(this);
    }

    private float mLastOffset;

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        int realCurrentPosition;
        int nextPosition;
//        float baseElevation = HeaderAdapter.BASE_ELEVATION;
        float realOffset;
        boolean goingLeft = mLastOffset > positionOffset;

        // If we're going backwards, onPageScrolled receives the last position
        // instead of the current one
        if (goingLeft) {
            realCurrentPosition = position + 1;
            nextPosition = position;
            realOffset = 1 - positionOffset;
        } else {
            nextPosition = position + 1;
            realCurrentPosition = position;
            realOffset = positionOffset;
        }

        // Avoid crash on overscroll
        if (nextPosition > adapter.getCount() - 1
                || realCurrentPosition > adapter.getCount() - 1) {
            return;
        }


        View currentCard = adapter.getViewAt(realCurrentPosition);

        // This might be null if a fragment is being used
        // and the views weren't created yet
        if (currentCard != null) {
            currentCard.setScaleX((float) (1 + 0.4 * (1 - realOffset)));
            currentCard.setScaleY((float) (1 + 0.4 * (1 - realOffset)));
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                currentCard.setElevation((baseElevation +baseElevation* (HeaderAdapter.MAX_ELEVATION_FACTOR - 1) * (1 - realOffset)));
//            }
        }

        View nextCard = adapter.getViewAt(nextPosition);

        // We might be scrolling fast enough so that the next (or previous) card
        // was already destroyed or a fragment might not have been created yet
        if (nextCard != null) {
            nextCard.setScaleX((float) (1 + 0.4 * (realOffset)));
            nextCard.setScaleY((float) (1 + 0.4 * (realOffset)));
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                nextCard.setElevation((baseElevation + baseElevation* (HeaderAdapter.MAX_ELEVATION_FACTOR - 1) * (realOffset)));
//            }
        }

        mLastOffset = positionOffset;
    }

    //    int[] headerBackgroundImages = {R.drawable.header_n1,R.drawable.header_n2};//,R.drawable.header_n3
    int currentPosition;

    @Override
    public void onPageSelected(int position) {
        //之前选中的点设置为默认背景
        View preSelectedItem = adapter.getViewAt(currentPosition);
        if (preSelectedItem != null) {
//            SimpleDraweeView header_iv2 = (SimpleDraweeView) preSelectedItem.getTag();
//            header_iv2.setBackgroundResource(R.drawable.reai_header_bg);
            preSelectedItem.setScaleX(1);
            preSelectedItem.setScaleY(1);
        }
        View selectedItem = adapter.getViewAt(position);
        if (selectedItem != null) {
//            int i = position%headerBackgroundImages.length;
//            SimpleDraweeView header_iv = (SimpleDraweeView) selectedItem.getTag();
//            header_iv.setBackgroundResource(headerBackgroundImages[i]);
            selectedItem.setScaleX(1.4f);
            selectedItem.setScaleY(1.4f);
        }

        //TODO 执行动画
        lastAnimationTime = System.currentTimeMillis();
        if (currentPosition > position) {
            animationRight();//向右滑动
        } else if (currentPosition < position) {
            animationLeft();//向左滑动
        }

        currentPosition = position;
        if (listener != null) {
            listener.onChange(position);
        }
    }


    public void resetHeaderView(int position){


//        bgId = 0;
//        card_view_shadow.setBackgroundResource(R.drawable.card_green);
    }

    int[] cardBg = {R.drawable.card_green, R.drawable.card_blue};

    private void animationLeft() {
        setupShadowView();
        final int width = PlatformUtil.windowWidth((Activity) card_view.getContext());
        ObjectAnimator animator = ObjectAnimator.ofFloat(card_view, "translationX", 0, -width).setDuration(600);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animatedValue = (float) animation.getAnimatedValue();
                card_view_shadow.setTranslationX(animatedValue + width);
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                card_view_shadow.setVisibility(View.VISIBLE);
                card_view_shadow.setBackgroundResource(cardBg[bgId]);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                card_view.setTranslationX(0);
                card_view.setBackgroundResource(cardBg[bgId]);
                card_view_shadow.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });

        animator.start();
    }

    int bgId = 0;

    private void setupShadowView() {
        bgId = (++bgId) % cardBg.length;
        card_view_content.destroyDrawingCache();
        card_view_content.setDrawingCacheEnabled(true);
        card_view_content.buildDrawingCache();
        Bitmap drawingCache = card_view_content.getDrawingCache();
        card_view_shadow.setImageBitmap(drawingCache);
    }

    private void animationRight() {
        setupShadowView();
        final int width = PlatformUtil.windowWidth((Activity) card_view.getContext());
        ObjectAnimator animator = ObjectAnimator.ofFloat(card_view, "translationX", 0, width).setDuration(600);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float animatedValue = (float) animation.getAnimatedValue();
                card_view_shadow.setTranslationX(animatedValue - width);
            }
        });

        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                card_view_shadow.setVisibility(View.VISIBLE);
                card_view_shadow.setBackgroundResource(cardBg[bgId]);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                card_view.setTranslationX(0);
                card_view.setBackgroundResource(cardBg[bgId]);
                card_view_shadow.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });

        animator.start();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void transformPage(View page, float position) {
    }

    private long lastAnimationTime;//上次执行动画的时间

    @Override
    public void onItemClick(int position) {
        if (currentPosition == position) {
//            MyLogger.jLog().i("点击正中间的view");

            if (listener != null) {
                listener.onClick(position);
            }
        } else {
            long l = System.currentTimeMillis();
            if (l - lastAnimationTime > 1000) {//如果距离上一次执行动画，超过一定的时间，才允许再次点击
                viewPager.setCurrentItem(position, true);
            }
        }
    }

    @Override
    public void onItemLongClick(int position) {
        if (currentPosition == position) {
            if (listener != null) {
                listener.onLongClick(position);
            }
        }
    }

    private SelectedTerminalChangeListener listener;

    public void setListener(SelectedTerminalChangeListener listener) {
        this.listener = listener;
    }


    public interface SelectedTerminalChangeListener {
        void onChange(int position);

        void onClick(int position);

        void onLongClick(int position);
    }


    public void old() {
        cardBg = new int[]{R.drawable.card_green_old, R.drawable.card_blue_old};
//        card_view.setBackgroundResource(cardBg[bgId]);
    }


    public void child() {
        cardBg = new int[]{R.drawable.card_green, R.drawable.card_blue};
//        card_view.setBackgroundResource(cardBg[bgId]);
    }

}
